﻿// Copyright (c) Appeon. All rights reserved.
// Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. 
// You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0.

using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;

namespace SnapObjects.Data.SqlServer
{
    internal class SqlServerSqlColumnSchemaProvider : SqlColumnSchemaProvider
    {
        private readonly string _sqlFormat = "exec [sys].sp_describe_undeclared_parameters N'{0}'";

        public SqlServerSqlColumnSchemaProvider(DataContext context) : base(context)
        {
        }

        public override IReadOnlyList<IAdoDbParameter> GetSqlParameterSchema(string sqlText)
        {
            if (_dataContext.SqlExecutor is SqlExecutor sqlExecutor)
            {
                var sql = this.GetSqlText(sqlText);

                var result = sqlExecutor.Select<DynamicModel>(sql, false);

                return this.BuildAdoParameter(result);
            }

            return base.GetSqlParameterSchema(sqlText);
        }

        public override async Task<IReadOnlyList<IAdoDbParameter>> GetSqlParameterSchemaAsync(
            string sqlText, CancellationToken cancellationToken)
        {
            
            if (_dataContext.SqlExecutor is SqlExecutor sqlExecutor)
            {
                var sql = this.GetSqlText(sqlText);

                var result = await sqlExecutor.SelectAsync<DynamicModel>(sql, false, new object[] { }, cancellationToken);

                return this.BuildAdoParameter(result);
            }

            return await base.GetSqlParameterSchemaAsync(sqlText, cancellationToken);
        }

        protected override bool IsTimestamp(DataRow row, IDataReader reader)
        {
            var typeName = this.ColumnDataTypeName(row, reader);
            var isExpression = this.IsExpression(row, reader);
            var dataType = this.ColumnDataType(row, reader);

            if ("Timestamp".Equals(typeName, StringComparison.OrdinalIgnoreCase) &&
                isExpression &&
                dataType == typeof(byte[]))
            {
                return true;
            }

            return false;
        }

        protected override bool IsIdentity(DataRow row, IDataReader reader)
        {
            var isIdentity = base.IsIdentity(row, reader);

            if (!isIdentity)
            {
                var column = row.Table.Columns["isautoincrement"];

                var value = row.ItemArray[column.Ordinal];

                return this.GetSchemaItemValue<bool>(value);
            }

            return isIdentity;
        }

        protected override bool IsReadOnly(DataRow row, IDataReader reader)
        {
            var column = row.Table.Columns["isreadonly"];

            var value = row.ItemArray[column.Ordinal];

            return this.GetSchemaItemValue<bool>(value);
        }

        protected override bool IsAliased(DataRow row, IDataReader reader)
        {
            var column = row.Table.Columns["isaliased"];

            var value = row.ItemArray[column.Ordinal];

            return this.GetSchemaItemValue<bool>(value);
        }

        protected override IList<string> GetNotInWhereType()
        {
            return new List<string>() { "text" };
        }

        private IReadOnlyList<IAdoDbParameter> BuildAdoParameter(IList<DynamicModel> parameters)
        {
            var adoParms = new List<IAdoDbParameter>();

            foreach (var parm in parameters)
            {
                var name = parm.GetValue<string>(1);
                var typeName = parm.GetValue<string>(3);

                if (typeName.StartsWith("datetime2", StringComparison.OrdinalIgnoreCase))
                {
                    typeName = "datetime2";
                }

                adoParms.Add(new AdoDbParameter(name, null, typeof(object))
                {
                    TypeName = typeName,
                });
            }

            return adoParms;
        }

        private string GetSqlText(string sqlText)
        {
            if (!String.IsNullOrWhiteSpace(sqlText))
            {
                return String.Format(_sqlFormat, sqlText.Replace("'", "''"));
            }

            return sqlText;
        }
    }
}
